package sk.octopuss.archery.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import sk.octopuss.archery.dao.UserDao;
import sk.octopuss.archery.domain.User;

@Service("openIdUserDetailsService")
public class OpenIdUserDetailsServiceImpl  implements UserDetailsService {
	
	@Autowired
	private UserDao userDao;
	@Autowired 
	private UserAssembler assembler;
	
	    @Override
		public UserDetails loadUserByUsername(final String openIdIdentifier)  throws UsernameNotFoundException, DataAccessException {
	        final User user= userDao.findByOpenId(openIdIdentifier);
	      
	        if (user == null) {
	            throw new UsernameNotFoundException("User not found for OpenID: " + openIdIdentifier);
	        } else {
	            if (!user.isActive()) {
	                throw new DisabledException("User is disabled");
	            }
	            return assembler.buildUserFromUserEntity(user);
	        }
	    }
}
